<template>
    <div class="main-content">
        <ElForm
            ref="searchFormRef"
            :model="searchForm"
            inline
            class="search-form"
            label-width="68px"
            label-position="left">
            <ElFormItem label="姓名" prop="realName">
                <ElInput
                    v-model="searchForm.realName"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>
            <ElFormItem label="帐号" prop="userName">
                <ElInput
                    v-model="searchForm.userName"
                    size="default"
                    placeholder="请输入"
                ></ElInput>
            </ElFormItem>

            <ElFormItem label="角色" prop="roleName">
                <ElSelect

                    v-model="searchForm.roleName"
                    size="default"

                    placeholder="请选择"
                >
                    <el-option
                    v-for="item in roleOps"
                    :key="item.roleId"
                    :value="item.roleName"
                    :label="item.roleName">

                    </el-option>
                </ElSelect>
            </ElFormItem>

            <ElFormItem>
                <ElButton
                    size="default"
                    color="#4371EE"
                    @click="reset(false)"
                >
                    查询
                </ElButton>
                <ElButton
                    size="default"
                    plain=""
                    @click="reset(true)"
                >
                    重置
                </ElButton>
            </ElFormItem>
        </ElForm>
            <!-- </ElCol> -->
            <div class="btns">
                <ElButton

                    class="add-btn"
                    color="#4371EE"
                    size="default"
                    :icon="Plus"
                    @click="addShow = true"
                >
                    添加用户
                </ElButton>
            </div>
            <ElTable
                border
                id="userTable"
                class="table"
                :data="tableData"
                :style="{ height: `${maxTableHeight}px`, overflow: 'auto' }"
            >
                <ElTableColumn prop="userName" label="帐号" />

                <ElTableColumn prop="realName" label="姓名" />
                <ElTableColumn prop="mobilePhone" label="电话" />
                <ElTableColumn prop="belongRole" label="角色" />
                <ElTableColumn prop="status" label="状态" >
                    <template #default="scope">
                        {{ statusOps.find(({ value }) => value == scope.row.status).label }}
                    </template>
                </ElTableColumn>
                <ElTableColumn prop="createTime" label="创建时间" />
                <ElTableColumn prop="updateTime" label="更新时间" />

                <ElTableColumn  fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <ElButton

                            link
                            type="text"
                            size="default"
                            @click="editFun(scope.row)"
                        >
                            修改
                        </ElButton>
                        <ElButton

                        link
                        type="text"
                        size="default"
                        @click="handleEnable(scope.row)"
                        >
                        {{ scope.row.status == 0 ? '解锁' : '锁定'}}
                        </ElButton>
                        <ElButton  link type="text" size="default" @click="handleDelete(scope.row)">
                            删除
                        </ElButton>

                    </template>
                </ElTableColumn>
            </ElTable>

            <ElPagination
                class="pagination"
                background
                layout="total,sizes,prev, pager, next,jumper"
                :total="total"
                :current-page="searchForm.pageNum"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="searchForm.pageSize"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />

            <!--新增或编辑角色-->
            <ElDialog   class="main-dialog" v-model="addShow"  :title="addForm.userId ? '修改用户' : '添加用户'" width="480px">
                <div class="dialog-form">
                    <ElForm
                        ref="addFormRef"
                        :model="addForm"
                        :rules="rules"
                        label-width="80px"
                        label-position="left"
                    >
                        <ElFormItem label="帐号" prop="userName">
                            <el-input v-model="addForm.userName" :disabled="!!addForm.userId" size="default" placeholder="请输入帐号"  />
                        </ElFormItem>

                        <ElFormItem label="密码" prop="password">
                            <el-input v-model="addForm.password" size="default" placeholder="请输入密码" />
                        </ElFormItem>
                        <ElFormItem label="姓名" prop="realName">
                            <el-input v-model="addForm.realName" size="default" placeholder="请输入真实姓名"  />
                        </ElFormItem>
                        <ElFormItem label="手机号" prop="mobilePhone">
                            <el-input v-model="addForm.mobilePhone" size="default" placeholder="请输入手机号"  />
                        </ElFormItem>

                        <ElFormItem label="角色">
                            <ElSelect

                                v-model="addForm.roleIds"
                                size="default"
                                multiple
                                placeholder="请选择"
                            >
                             <el-option
                             v-for="item in roleOps"
                             :key="item.roleId"
                             :value="item.roleId"
                             :label="item.roleName">

                             </el-option>
                            </ElSelect>
                        </ElFormItem>
                    </ElForm>

                </div>
                <template #footer>
                    <span  class="dialog-footer">
                        <ElButton size="default" @click="addShow = false">取 消</ElButton>
                        <ElButton color="#4371EE" size="default" @click="submitForm(addFormRef)">提 交</ElButton>
                    </span>
                </template>

            </ElDialog>



    </div>
</template>

<script setup lang="ts">
import useTableSetting from '@/hooks/useTableSetting';
import { ref, onMounted, reactive, nextTick, watch } from 'vue';
import md5 from 'js-md5';
import { addUser, editUser, delUser, userList, roleList} from '@/api/index.ts';

import { ElMessage, ElTree, FormInstance, ElMessageBox } from 'element-plus';

import { getFlatDeepTreeData } from '@/utils/common';
import { Search, Plus } from '@element-plus/icons-vue';
import { validateForm } from '@/helper/index';


const statusOps = [
    { label: '锁定', value: 0 },
    { label: '未锁定', value: 1 },

];
const tableData: any = ref([]);
const roleOps = ref([]);
const getRoleList = async () => {
    const { list } = await roleList( {pageNum: 1, pageSize: 1000});
    roleOps.value = list;
};

getRoleList();


const searchFormRef = ref<FormInstance>(null);

const details = ref({});


const searchForm = reactive<searchFormType>({
    realName: '',
    userName: '',
    roleName: '',

    pageNum: 1,
    pageSize: 20,
});
const total = ref<number>(0);


const rules = reactive({
    userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
    password: [
        { pattern:/^.{6,}$/, message: '密码长度至少是6位', trigger: 'blur' }
    ]
});



const getList = async () => {
    try {
        const res: any = await userList(searchForm);
        tableData.value = res.list;

        total.value = res.total;
    } catch (err) {}
};

const handleDelete = async (row) => {

    await ElMessageBox.confirm('确认要删除吗？', '提示', {
        confirmButtonText: '确  定',
        cancelButtonText: '取  消',
        type: 'warning'
    });
    await delUser({ userId: row.userId});
    ElMessage.success('删除成功！');
    reset();
};

const goDetail = (row) => {
    details.value = JSON.parse(JSON.stringify(row));
};



const reset = (reset: boolean) => {
    if(reset) {
        searchFormRef.value.resetFields();
    }
    searchForm.pageNum = 1;
    getList();
};

const handleSizeChange = (rows: number) => {
    searchForm.pageNum = 1;
    searchForm.pageSize = rows;
    getList();
};
const handleCurrentChange = (page: number) => {
    searchForm.pageNum = page;
    getList();
};


const addShow = ref<boolean>(false);
const addFormRef = ref<FormInstance>(null);
const addForm = reactive<addUserType>({
    userId: '',
    'mobilePhone': '',
    'password': '',
    'realName': '',
    'roleIds': '',
    'userName': ''
});

const resetForm = (form) => {
    Object.keys(form).forEach(key => addForm[key] = '');
};

watch(
    addShow,
    val => {
        if(!val) {
            addFormRef.value.clearValidate();
            resetForm(addForm);
        }
    }
);

const submitForm = async (formEl: FormInstance | undefined) => {
    await validateForm(formEl);
    const params = {
        ...addForm,
        roleIds: addForm.roleIds.join(','),

    };
    if(addForm.password) {
        params.password = md5(addForm.password).substr(8, 16);
    }
    addForm.userId ? await editUser(params) : await addUser(params);
    ElMessage.success('操作成功！');
    addShow.value = false;
    reset();
};



const editFun = async (row: any) => {
    addShow.value = true;
    Object.keys(row).forEach(key => {
        if(key in addForm && key !== 'belongRoleIds') {
            addForm[key] = row[key];

        } else if(key === 'belongRoleIds') {
            addForm.roleIds = row.belongRoleIds.split(',').map(id => +id);
        }
    });
};


const handleEnable  = async (row: any) => {
    const params = {
        userId : row.userId,
        status : 1- row.status,
        roleIds: row.belongRoleIds
    }
    await editUser(params)
    ElMessage.success(row.status === 0 ? '解锁成功' : '锁定成功');
    getList()
};




onMounted(() => {

    getList();
});
const { maxTableHeight, setTableMaxHeight } = useTableSetting({ id: 'userTable', offsetBottom: 92 });
</script>

<style scoped lang="scss">
.main-content > .btns{
    margin:10px 0 20px;
}
.search-form{
   ::v-deep(){
    .el-input,.el-select{
        width: 265px !important;
    }
   }
}
</style>

